﻿using System;
using Newtonsoft.Json;

namespace Megaplan.API.Extentions
{
    public class DeadLineConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(DateTime?));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (string.IsNullOrEmpty(reader.Value.ToString()))
            {
                return null;
            }
            var source = reader.Value.ToString();
            
            if(source.EndsWith(":"))
            {
                source = source + "00";
            }

            DateTime outValue;
            if( DateTime.TryParse(source, out outValue))
            {
                return outValue;
            }
            else
            {
                var space = source.IndexOf(" ");
                source.Remove(space);

                return DateTime.Parse(source);
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            // Left as an exercise to the reader :) 
            throw new NotImplementedException();
        }
    } 

}
